﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using SixApp.Core;
using SixApp.Data;
using SixApp.Entities;

namespace SixApp.Repositories
{
    public class FormulaRepository : BaseRepository
    {
        //public EntityList<Formula> GetFormulas(FormulaType formulaType)
        //{
        //    StringBuilder sbSql = new StringBuilder();
        //    Dictionary<string, object> args = new Dictionary<string, object>();

        //    sbSql.Append("select * from formula ");

        //    int formulaKind = (int)formulaType;
        //    if (formulaKind > 0)
        //    {
        //        sbSql.Append(" where zl = @zl ");
        //        args.Add("zl", formulaKind);
        //    }

        //    sbSql.Append(" order by cs ");

        //    DataTable dt =  AccessHelper.GetDataTable(sbSql.ToString(), args);


        //    var formulas = new EntityList<Formula>();
        //    formulas.Load(dt);

        //    return formulas;
        //}

        public DataTable GetFormulas(string formulaType)
        {
            StringBuilder sbSql = new StringBuilder();
            Dictionary<string, object> args = new Dictionary<string, object>();

            sbSql.Append("select * from formula ");

            if (!string.IsNullOrEmpty(formulaType))
            {
                sbSql.Append(" where lx = @lx ");
                args.Add("lx", formulaType);
            }

            sbSql.Append(" order by cs ");

            DataTable dt = DbContext.GetDataTable(sbSql.ToString(), args);

            return dt;
        }

        public void SaveOrUpdate(Formula formula)
        {
            StringBuilder sbSql = new StringBuilder();
            Dictionary<string, object> args = new Dictionary<string, object>();

            if (formula.Id > 0)
            {
                sbSql.Append(" update formula set qx = @qx, gs = @gs, lx = @lx, xqs = @xqs, cs = @cs ")
                        .Append(" where id = " + formula.Id);
                //args.Add("id", formula.Id);
            }
            else
            {
                sbSql.Append(" insert into formula(qx, gs, lx, xqs, cs) ")
                        .Append(" values(@qx, @gs, @lx, @xqs, @cs) ");
            }

            args.Add("qx", formula.qx);
            args.Add("gs", formula.gs);
            args.Add("lx", formula.lx);
            args.Add("xqs", formula.xqs);
            args.Add("cs", formula.cs);

            DbContext.Execute(sbSql.ToString(), args);
        }

        public void DeleteFormula(long formulaId)
        {
            string sql = "delete from formula where id = @id";
            Dictionary<string, object> args = new Dictionary<string, object>();

            args.Add("id", formulaId);

            DbContext.Execute(sql, args);
        }
    }
}
